package core;

import branch.Branch;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import fileoperation.FileCreation;
import fileoperation.FileDeletion;
import fileoperation.FileReader;
import gitobject.Commit;
import gitobject.Tree;
import index.Index;
import repository.Repository;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;

public class JitCommit {
    // commit以后，生成一个tree对象，根据tree生成commit
    // .jit/HEAD里，存储currentBranch指针信息 “ref: refs/heads/branchDemo“
    /*
       |- logs
         |- refs
            |-  heads(本地分支信息)
              |-  master(文件)：记录本地master分支的commit信息
              |-  localBranchDemo(文件)：记录本地localBranchDemo分支的commit信息
            |-  remote(远程分支信息)
              |-  master(文件)：记录远程master分支的commit信息）
              |-  remoteBranchDemo(文件)：记录远程remoteBranchDemo分支的commit信息）
         |- HEAD(文件):记录本地全部分支的commit信息(切换分支时，父子的commitId都是自己)
    */

    public static void commit(String message) throws Exception {
        // commit后生成本次文件的提交目录所生成的tree对象
        Index index = new Index();
        LinkedList<String> treeList = index.getIndexList();
        Tree indexTree = new Tree(treeList);
        // 在objects里创建tree
        FileCreation.createDirectory(indexTree.getPath(), indexTree.getKey().substring(0, 2));
        FileCreation.createFile(indexTree.getPath() + File.separator + indexTree.getKey().substring(0, 2), indexTree.getKey().substring(2), "");
        indexTree.compressWrite();

        /*
        Commit(String treePath, String author, String committer, String message)
        Content of this commit, like this:
        tree bd31831c26409eac7a79609592919e9dcd1a76f2
        parent d62cf8ef977082319d8d8a0cf5150dfa1573c2b7
        author xxx  1502331401 +0800
        committer xxx  1502331401 +0800
        */
        String author = System.getProperty("user.name") + " " + "<664941471@qq.com>";
        String committer = System.getProperty("user.name") + " " + String.valueOf(new Date().getTime());
        Commit commit = new Commit(indexTree, author, committer, message);
        FileCreation.createDirectory(commit.getPath(), commit.getKey().substring(0, 2));
        FileCreation.createFile(commit.getPath() + File.separator + commit.getKey().substring(0, 2), commit.getKey().substring(2), "");
        commit.compressWrite();

        if(!new File(Branch.getRefsPath()+File.separator+"heads"+File.separator+"master").exists()){
            FileReader.writeValue(Repository.getGitDir()+File.separator+"HEAD","ref: refs/heads/master");
            FileCreation.createFile(Branch.getRefsPath()+File.separator+"heads", "master", "");
        }

        String currentBranchName = JitBranch.getCurrentBranchName();
        saveCommitInfo(currentBranchName, commit);
        updateLastCommit(currentBranchName, commit);

        System.out.println("Commit Create Successfully!");
        System.out.println(commit);
    }

    private static void updateLastCommit(String currentBranchName, Commit commit) throws IOException {
        File currentBranch = new File(Repository.getGitDir() + File.separator + "refs" + File.separator + "heads" + File.separator  + currentBranchName);
        /*
        ef8acb01ebde4e73478088e514727ac20a7a1736 de6b71b58f8d50ce0d5aed38c84503310a42dfcf
        孟鑫岩 <664941471@qq.com> 1639486763 +0800
        commit: test
        */
        String saveInfo = commit.getKey();
        FileReader.writeValue(currentBranch.getPath(),saveInfo);
    }

    // saveInfo在logs/HEAD中，同时save在currentBranchName中
    public static void saveCommitInfo(String currentBranchName, Commit commit) throws IOException {
        if (!new File(Repository.getGitDir() + File.separator + "logs").exists()) {
            JitLogs.initLogs();
        }

        /*
        ef8acb01ebde4e73478088e514727ac20a7a1736 de6b71b58f8d50ce0d5aed38c84503310a42dfcf
        孟鑫岩 <664941471@qq.com> 1639486763 +0800
        commit: test
        */
        File Head = new File(Repository.getGitDir() + File.separator + "logs" + File.separator + "Head");
        File currentBranch = new File(Repository.getGitDir() + File.separator + "logs" + File.separator + "refs" + File.separator + "heads" + File.separator + currentBranchName);


        String parentInfo = commit.getParent().isEmpty()?"0000000000000000000000000000000000000000":commit.getParent();
        String saveInfo =  parentInfo + " " + commit.getKey() + " "
                + System.getProperty("user.name") + " " + "<664941471@qq.com>" + " "
                + String.valueOf(new Date().getTime()) + " " + commit.getFmt() + ": " +commit.getMessage();

        String valueHead = FileReader.readValue(Head) +"\n" + saveInfo.trim() ;
        String valueBranch = FileReader.readValue(currentBranch) +"\n" + saveInfo.trim() ;
        FileReader.writeValue(Head.getPath(),valueHead);
        FileReader.writeValue(currentBranch.getPath(),valueBranch);
    }
}